<?php
/**
 *    退款维权管理员控制器
 *
 *    @author    Garbin
 *    @usage    none
 */
class RefundApp extends BackendApp {

    var $_order_mod;
    var $_order_log_mod;
    var $_order_extm_mod;
    var $_goods_mod;
    var $_ordergoods_mod;
    var $_refund_mod;
    var $_store_mod;
    var $_member_mod;
    var $_refund_message_mod;

    function __construct() {
        $this->RefundApp();
    }

    function RefundApp() {
        parent::__construct();
        $this->_order_mod = &m('order');
        $this->_order_log_mod = &m('orderlog');
        $this->_order_extm_mod = &m('orderextm');
        $this->_goods_mod = &m('goods');
        $this->_ordergoods_mod = &m('ordergoods');
        $this->_refund_mod = &m('refund');
        $this->_store_mod = &m('store');
        $this->_member_mod = &m('member');
        $this->_refund_message_mod = &m('refund_message');
    }

    function index() {
        $sort_order = str_replace('_', ' ', trim($_GET['sort_order']));
        if (!empty($sort_order)) {
            $order = $sort_order . ',created desc';
        } else {
            $order = 'created desc';
        }
        $ask_customer = trim($_GET['ask_customer']);
        if ($ask_customer == 'yes' || $ask_customer == 'no') {
            $ask_customer = $ask_customer == 'yes' ? 1 : 0;
            $conditions .= ' AND ask_customer=' . $ask_customer;
        } elseif ($ask_customer == 'all') {
            $conditions .= '';
        } else {
            $conditions .= '';
        }

        $sn = trim($_GET['sn']);
        if($sn){
            $conditions .= ' AND refund_sn like "%'.$sn.'%"';
            $this->assign('sn',$sn);
        }

        $page = $this->_get_page(10);   //获取分页信息
        $refunds = $this->_refund_mod->find(array(
            'conditions' => '1=1'.$conditions,
            'limit' => $page['limit'],
            'order' => $order,
            'count' => true
        ));
        $page['item_count'] = $this->_refund_mod->getCount();

        foreach ($refunds as $key => $refund) {
            $store = $this->_store_mod->get(array('conditions' => 'store_id=' . $refund['seller_id'], 'fields' => 'store_name,owner_name'));
            $refunds[$key]['store_name'] = $store['store_name'];
            $refunds[$key]['seller_name'] = $store['owner_name'];

            $member = $this->_member_mod->get(array('conditions' => 'user_id=' . $refund['buyer_id'], 'fields' => 'user_name'));
            $refunds[$key]['buyer_name'] = $member['user_name'];
            $goods = $this->_goods_mod->get(array('conditions' => 'goods_id=' . $refund['goods_id'], 'fields' => 'goods_name'));
            $refunds[$key]['goods_name'] = $goods['goods_name'];

            $order = $this->_order_mod->get(array('conditions' => 'order_id=' . $refund['order_id'], 'fields' => 'order_sn'));
            $refunds[$key]['order_sn'] = $order['order_sn'];
        }
        $this->_format_page($page);
        $this->assign('page_info', $page);
        $this->assign('filtered', $conditions? 1 : 0); //是否有查询条件

        $this->assign('refunds', $refunds);
        $this->display('refund.index.html');
    }

    function view() {
        $refund_id = empty($_GET['refund_id']) ? 0 : intval($_GET['refund_id']);
        if (!$refund_id) {
            $this->show_warning('refund_id_miss', 'back_list', 'index.php?app=refund&act=view&refund_id=' . $refund_id);
            return;
        }

        //  读取退款信息
        $refund = $this->_refund_mod->get($refund_id);

        if (!$refund) {
            $this->show_warning('refund_not_find', 'back_list', 'index.php?app=refund&act=view&refund_id=' . $refund_id);
            return;
        }

        if (!IS_POST) {
            $order = $this->_order_mod->get($refund['order_id']);
            $order['items'] = $this->_ordergoods_mod->find(array(
                'conditions' => 'order_id=' . $refund['order_id'],
            ));
            $order['shipping'] = $this->_order_extm_mod->get($refund['order_id']);


            $page = $this->_get_page(10);   //获取分页信息
            $refund['message'] = $this->_refund_message_mod->find(array(
                'conditions' => 'refund_id=' . $refund_id,
                'order' => 'created desc',
                'limit' => $page['limit'],
                'count' => true
            ));
            $page['item_count'] = $this->_refund_message_mod->getCount();
            $this->_format_page($page);
            $this->assign('page_info', $page);
            $this->assign('refund', $refund);
            $this->assign('order', $order);
            $this->display('refund.view.html');
        }


//        else {
//            $this->_check_post_data($refund);
//
//             if($_POST['checkresult']=='no')
//            {
//
//                $this->admin_log(Lang::get('refund_fail'),1);
//                $this->_refund_mod->edit($refund_id, array('status' => 'FAILED', 'end_time' => gmtime(), 'ask_customer' => 1));
//
//                $content = sprintf(Lang::get('admin_agree_refund_content_change'), Lang::get('system_customer'),'0','0','平台客服留言:'.$_POST['content']);
//                $data = array(
//                    'owner_id' => $refund['seller_id'],
//                    'owner_role' => 'seller',
//                    'refund_id' => $refund_id,
//                    'content' => $content,
//                    'created' => gmtime()
//                );
//                $this->_refund_message_mod->add($data);
//
//                $this->show_message('system_handle_refund_ok', 'back_list', 'index.php?app=refund&act=view&refund_id=' . $refund_id);
//                exit;
//            }
//            $order_id = $refund['order_id'];
//            $order_info = $this->_order_mod->get($order_id);
//
//
//            //在这判断更新订单类型  是否为心愿单订单
//            if($order_info['type'] == 'wishOrder'){
//                $wish = &m('wish');
//                $wishPayLog = &m('wish_pay_log');
//                $wishInfos = $wish->get(array('conditions'=>'order_id = '.$order_info['order_id']));
//                $wishInfo = $wishPayLog->find(array('conditions'=>'wish_id = '.$wishInfos['id']));
//                if(!empty($wishInfo)){
//                    $newArr = array();
//                    //查出心愿单共付几笔单数  遍历退款
//                    foreach($wishInfo as $k=>$v){
//                        $info['order_sn'] = $v['order_sn'];
//                        $newArr['total_fee'] = $v['money'];
//                        $info['payment_code'] = 'alipay_app';
//                        $newArr['refund_sn'] = $refund['refund_sn'];
//                        if($v['pay_type'] == 1){
//                            $info['payment_code'] = 'wxpay_app';
//                        }else{
//                            $info['payment_code'] = 'alipay_app';
//                        }
//                        $this->refundSign($newArr,$info);
//                    }
//                    $wish = &m("wish");
//                    $save = $wish->edit($wishInfo['wish_id'],array(
//                        'state' => 3
//                    ));
//                }
//            }else{
//                $this->refundSign($refund,$order_info);
//            }
//            $this->refundMethod($order_info,$refund_id,$_POST);
//            $this->show_message('system_handle_refund_ok', 'back_list', 'index.php?app=refund&act=view&refund_id=' . $refund_id);
//        }
    }

    //对三方支付进行退款封装
    function refundSign($refund,$order_info){

        ini_set('display_errors','on');
        error_reporting(E_ALL);

        $out_trade_no = $order_info["order_sn"];
        $total_fee = $refund["total_fee"] * 100;
        $refund_fee = $refund["total_fee"] * 100;
        $refund_alifee = $refund["total_fee"];
        if($order_info['payment_code'] == 'epaywxnative' || $order_info['payment_code'] == 'wxpay_app'){
            include_once ROOT_PATH."/includes/payments/epaywxnative/lib/WxPay1.Data.php";
            include_once ROOT_PATH."/includes/payments/epaywxnative/lib/WxPay1.Api.php";
            include_once ROOT_PATH."/includes/payments/epaywxnative/lib/WxPay1.Config.php";
            $input = new WxPayRefund();
            $input->SetOut_trade_no($out_trade_no);
            $input->SetTotal_fee($total_fee);
            $input->SetRefund_fee($refund_fee);
            $config = new WxPay1Config();
            $input->SetOut_refund_no($refund['refund_sn']);
//            $input->SetOp_user_id($config->GetMerchantId());
            $rs = WxPay1Api::refund($config,$input, 60);
//                $this->printf_info(WxPay1Api::refund($config,$input, 60));
            if($rs['return_code'] != 'SUCCESS'){
                $this->show_warning('退款失败', 'back_list', 'index.php?app=refund');
                return;
            }
        }else if($order_info['payment_code'] == 'epayalipay' || $order_info['payment_code'] == 'alipay_app'){
            $config = include_once ROOT_PATH."/includes/payments/epayalipay/epayalipayrefund/config.php";
            include_once ROOT_PATH."/includes/payments/epayalipay/epayalipayrefund/pagepay/service/AlipayTradeService.php";
            include_once ROOT_PATH."/includes/payments/epayalipay/epayalipayrefund/pagepay/buildermodel/AlipayTradeRefundContentBuilder.php";
            //商户订单号，商户网站订单系统中唯一订单号
            $out_trade_no = trim($out_trade_no);

            //支付宝交易号
//                $trade_no = trim($_POST['WIDTRtrade_no']);
            //请二选一设置

            //需要退款的金额，该金额不能大于订单金额，必填
            $refund_amount = trim($refund_alifee);

            //退款的原因说明
//                $refund_reason = trim($_POST['WIDTRrefund_reason']);

            //标识一次退款请求，同一笔交易多次退款需要保证唯一，如需部分退款，则此参数必传
//                $out_request_no = trim($_POST['WIDTRout_request_no']);

            //构造参数
            $RequestBuilder=new AlipayTradeRefundContentBuilder();
            $RequestBuilder->setOutTradeNo($out_trade_no);
//                $RequestBuilder->setTradeNo($trade_no);
            $RequestBuilder->setRefundAmount($refund_amount);
//                $RequestBuilder->setOutRequestNo($out_request_no);
//                $RequestBuilder->setRefundReason($refund_reason);
            $aop = new AlipayTradeService($config,true);

            $response = $aop->Refund($RequestBuilder);
            $rs = json_decode($response,true);
            if($rs['code'] == '10000'){
            }else{
                $this->_member_mod->db->query('rollback');
                $this->show_warning('退款失败', 'back_list', 'index.php?app=refund');
                return;
            }
        }
    }

    //对退款退货进行封装
    function refundMethod($order_info,$refund_id,$newArr){
        if ($order_info['payment_code'] == 'cod' || $order_info['payment_code'] == 'bank' || $order_info['payment_code'] == 'post' || $order_info['payment_code'] == '') {
            $this->show_warning('payment_not_support_refund', 'back_list', 'index.php?app=refund');
            return;
        }
        //判断是否已完成,如果未完成先结束订单
        $this->auto_refund_confirm_order($order_info);
        //修改管理员设置价格 ， 重新获取 信息
        $refund_shipping_fee = $newArr['refund_shipping_fee'] ? $newArr['refund_shipping_fee'] : 0;
        $this->_member_mod->db->query('start transaction');
        $refund = $this->_refund_mod->get($refund_id);
        if(($refund['refund_goods_fee'] != floatval($newArr['refund_goods_fee'])) || ($refund['refund_shipping_fee'] != $refund_shipping_fee)){
            $refund['refund_goods_fee']=floatval($newArr['refund_goods_fee']);
            $refund['refund_shipping_fee']=$refund_shipping_fee;
            $mysql_flag=$this->_refund_mod->edit($refund_id, array('refund_goods_fee' => $refund['refund_goods_fee'], 'refund_shipping_fee' => $refund['refund_shipping_fee']));
            if(!$mysql_flag){
                $this->_member_mod->db->query('rollback');
                $this->show_warning('系统繁忙，请重试');return;
            }
        }
        //退款金额
        $money = $refund['refund_goods_fee'] + $refund['refund_shipping_fee'];
        $time = gmtime();
        //同意退款,卖家扣除金额。
        $seller_data = array(
            'user_id' => $order_info['seller_id'],
            'user_name' => '',
            'order_id' => $order_info['order_id'],
            'order_sn' => $order_info['order_sn'],
            'type' => ACCOUNT_TYPE_REFUND_OUT,
            'money_flow' => 'outlay',
            'money' => $money,
            'complete' => 1,
            'log_text' => '您同意给买家' . $order_info['buyer_name'] . '购买的产品退款' . $money . '元，订单号为:' . $order_info['order_sn'] . ',退款编号为:' . $refund_id,
            'add_time' => $time,
        );

        $mysql_flag =$this->_member_mod->change_money($seller_data);
        if(!$mysql_flag){
            $this->_member_mod->db->query('rollback');
            $this->show_warning('系统繁忙，请重试');return;
        }

        //同意退款,买家增加金额
//            $buyer_data = array(
//                'user_id' => $order_info['buyer_id'],
//                'user_name' => '',
//                'order_id' => $order_info['order_id'],
//                'order_sn' => $order_info['order_sn'],
//                'type' => ACCOUNT_TYPE_REFUND_IN,
//                'money_flow' => 'income',
//                'money' => $money,
//                'complete' => 1,
//                'log_text' => $order_info['seller_name'] . '同意给你购买的产品退款' . $money . '元，订单号为:' . $order_info['order_sn'] . ',退款编号为:' . $refund_id,
//                'add_time' => $time,
//            );
//            $mysql_flag =$this->_member_mod->change_money($buyer_data);
//            if(!$mysql_flag){
//                $this->_member_mod->db->query('rollback');
//                $this->show_warning('系统繁忙，请重试');return;
//            }

        // 对 退货进行处理 BEGUN
        $mysql_flag =$this->_refund_mod->edit($refund_id, array('status' => 'SUCCESS', 'end_time' => gmtime(), 'ask_customer' => 1));
        if(!$mysql_flag){
            $this->_member_mod->db->query('rollback');
            $this->show_warning('系统繁忙，请重试');return;
        }
        $content = sprintf(Lang::get('admin_agree_refund_content_change'), Lang::get('system_customer'), $refund['refund_goods_fee'], $refund['refund_shipping_fee'], $newArr['content']);
        $data = array(
            'owner_id' => $order_info['sel  ler_id'],
            'owner_role' => 'seller',
            'refund_id' => $refund_id,
            'content' => $content,
            'created' => gmtime()
        );
        $this->_refund_message_mod->add($data);

        // 对 退货进行处理 END
        $this->_member_mod->db->query('commit');
        $this->admin_log(Lang::get('refund_suc'),1);

    }




    //当卖家同意退款 订单自动确认收货
    function auto_refund_confirm_order($order_info) {

        $order_id = $order_info['order_id'];

        //判断订单是否已完成，未完成订单则自动完成
        if ($order_info['status'] != ORDER_FINISHED) {
            $this->_order_mod->db->query('start transaction');
//            lichen 2019/6/21 start
            $mysql_flag=$this->_order_mod->edit($order_info['order_id'], array('status' => 50, 'finished_time' => gmtime()));
//            $mysql_flag=$this->_order_mod->edit($order_info['order_id'], array('status' => ORDER_FINISHED, 'finished_time' => gmtime()));
//            lichen 2019/6/21 end
            if(!$mysql_flag){
                $this->_member_mod->db->query('rollback');
                $this->show_warning('系统繁忙，请重试');exit;
            }
            /* 记录订单操作日志 */
            $order_log = & m('orderlog');
            $order_log->add(array(
                'order_id' => $order_id,
                'operator' => 0,
                'order_status' => order_status($order_info['status']),
                'changed_status' => order_status(ORDER_FINISHED),
                'remark' => Lang::get('admin_agree_refund_order_status_change'),
                'log_time' => gmtime(),
                'operator_type' => 'seller',
            ));


            /* 更新定单状态 开始***************************************************** */
            $this->account_mod_log = & m('account_log');
            $account_log_row = $this->account_mod_log->getrow("select * from " . DB_PREFIX . "account_log where order_id='$order_id' and type=" . ACCOUNT_TYPE_BUY);
            $sell_user_id = $order_info['seller_id']; //卖家ID
            $buyer_user_id = $account_log_row['user_id']; //买家ID
            if ($account_log_row['order_id'] == $order_id) {

                $temp_order = $this->_order_mod->get($order_id);
                $money = $temp_order['order_amount']; //定单价格

                $sell_money_row = $this->_member_mod->getAll('SELECT * FROM '.$this->_member_mod->table.' WHERE user_id='.$sell_user_id.' FOR UPDATE');
                if(is_array($sell_money_row) && !empty($sell_money_row)){
                    $sell_money_row= current($sell_money_row);
                $sell_money = $sell_money_row['money']; //卖家的资金
                $sell_money_dj = $sell_money_row['money_dj']; //卖家的冻结资金
                $new_money = $sell_money + $money;
                $new_money_dj = $sell_money_dj - $money;
                //更新数据
                $new_money_array = array(
                    'money' => $new_money,
                    'money_dj' => $new_money_dj,
                );
                $new_buyer_account_log = array(
                    'money' => $money,
                    'complete' => 1,
                    'states' => 40,
                );
                $new_seller_account_log = array(
                    'money' => $money,
                    'complete' => 1,
                    'states' => 40,
                );
                $mysql_flag=$this->_member_mod->edit('user_id=' . $sell_user_id, $new_money_array);
                if(!$mysql_flag){
                    $this->_member_mod->db->query('rollback');
                    $this->show_warning('系统繁忙，请重试');exit;
                }
                $mysql_flag=$this->account_mod_log->edit("order_id={$order_id} AND user_id={$sell_user_id} AND type=".ACCOUNT_TYPE_SELLER." AND money_flow='income' AND complete=0", $new_seller_account_log);
                if(!$mysql_flag){
                    $this->_member_mod->db->query('rollback');
                    $this->show_warning('系统繁忙，请重试');exit;
                }
                $mysql_flag=$this->account_mod_log->edit("order_id={$order_id} AND user_id={$buyer_user_id} AND type=".ACCOUNT_TYPE_BUY." AND money_flow='outlay' AND complete=0", $new_buyer_account_log);
                if(!$mysql_flag){
                    $this->_member_mod->db->query('rollback');
                    $this->show_warning('系统繁忙，请重试');exit;
                }
                }else{
                    $this->_member_mod->db->query('rollback');
                    $this->show_warning('卖家不存在');exit;
                }

            }
            /* 更新定单状态 结束***************************************************** */
            $this->_order_mod->db->query('commit');
        }
    }

    function _check_post_data($refund = array()) {

        if ($refund['status'] == 'SUCCESS' || $refund['status'] == 'CLOSED' || $refund['status'] == 'FAILED') {
            $this->show_warning('add_refund_message_not_allow');
            exit;
        }
        if (empty($_POST['refund_goods_fee']) || floatval($_POST['refund_goods_fee']) < 0) {
            $this->show_warning('refund_fee_ge0');
            exit;
        } elseif (floatval($_POST['refund_goods_fee']) > $refund['goods_fee']) {
            $this->show_warning('refund_fee_error');
            exit;
        }
        if ($_POST['refund_shipping_fee'] != '' && floatval($_POST['refund_shipping_fee']) < 0) {
            $this->show_warning('refund_shipping_fee_ge0');
            exit;
        }
        if (floatval($_POST['refund_shipping_fee']) > $refund['shipping_fee']) {
            $this->show_warning('refund_shipping_fee_error');
            exit;
        }
    }

    function printf_info($data)
    {
        foreach($data as $key=>$value){
            echo "<font color='#f00;'>$key</font> : ".htmlspecialchars($value, ENT_QUOTES)." <br/>";
        }
    }
    /**之前的退款操作 已废弃 start **/
//    function updateTpe(){
//        ini_set('display_errors','on');
//        error_reporting(E_ALL);
//        $refund_id = empty($_GET['id']) ? 0 : intval($_GET['id']);
//        if (!$refund_id) {
//            $this->show_warning('refund_id_miss', 'back_list', 'index.php?app=refund&act=view&refund_id=' . $refund_id);
//            return;
//        }
//
//        //查询订单信息
//
//
//        $data['type'] = $_GET['type'];
//        $data['status'] = 'WAIT_ADMIN_AGREE';
//        $refund = $this->_refund_mod->get(array('conditions'=>'refund_id = '.$refund_id));
//        $order_info = $this->_order_mod->get($refund['order_id']);
//        if($data['type'] == 2){
//            $data['status'] = 'REFUND_GOODS';
//
//        }else{
//
//            //在这判断更新订单类型  是否为心愿单订单
//            if($order_info['type'] == 'wishOrder'){
//                $wish = &m('wish');
//                $wishPayLog = &m('wish_pay_log');
//                $wishInfos = $wish->get(array('conditions'=>'order_id = '.$order_info['order_id']));
//                $wishInfo = $wishPayLog->find(array('conditions'=>'wish_id = '.$wishInfos['id']));
//                if(!empty($wishInfo)){
//                    $newArr = array();
//                    //查出心愿单共付几笔单数  遍历退款
//                    foreach($wishInfo as $k=>$v){
//                        $info['order_sn'] = $v['order_sn'];
//                        $newArr['total_fee'] = $v['money'];
//                        $newArr['refund_sn'] = $refund['refund_sn'];
//                        if($v['pay_type'] == 1){
//                            $info['payment_code'] = 'wxpay_app';
//                        }else{
//                            $info['payment_code'] = 'alipay_app';
//                        }
//                        $this->refundSign($newArr,$info);
//                    }
//                    $wish = &m("wish");
//                    $save = $wish->edit($wishInfos['id'],array(
//                        'state' => 3
//                    ));
//                }
//            }else{
//                $this->refundSign($refund,$order_info);
//            }
//            $data['status'] = 'SUCCESS';
//        }
//        $res = $this->_refund_mod->edit($refund_id,$data);
//        if(!$res){
//            $this->show_warning('操作失败');
//            return;
//        }
//
//        if($data['type'] == 2){
//            $refund_array = array(
//                'OrderNo' => $order_info['order_sn'],
//                'Note' => $refund['refund_reason'],
//                'CopName' => '',
//                'TrackingNo' => '',
//                'Action' => 1
//            );
//
//            $send_array = array(
//                'ClientGuid' => 'a8c7aa5c-851c-40f3-8a84-777a5dc97a26',
//                'ClientName' => 'ASA-OMS',
//                'CustomerRefundsInfo' => $refund_array
//            );
//            $rs = $this->sync_data('http://oms.jingjing.shop/api/order/CustomerRefunds', $send_array);
//            if(!$rs || $rs['code'] != '200'){
//                $this->show_warning('请求OMS失败');
//                return;
//            }
//        }
//        $this->admin_log(Lang::get('refund_suc'),1);
//        $this->show_message('system_handle_refund_ok', 'back_list', 'index.php?app=refund&act=view&refund_id=' . $refund_id);
//    }
    /**之前的退款操作 已废弃 end **/

    function status(){
        $refund_id = empty($_GET['id']) ? 0 : intval($_GET['id']);
        if (!$refund_id) {
            $this->show_warning('refund_id_miss', 'back_list', 'index.php?app=refund&act=view&refund_id=' . $refund_id);
            return;
        }



    }

    /**curl OMS请求**/
    function sync_data($url, $data_string)
    {
        $data_string = json_encode($data_string);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // https请求 不验证证书和hosts
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json; charset=utf-8',
                'Content-Length: ' . strlen($data_string))
        );
        ob_start();
        $res = curl_exec($ch);
        if (!$res) {
            return false;
        } else {
        return json_decode($res,true);
        }
        return array('code' => $return_code, 'result' => $return_content);
    }

    /**选择退款申请是否同意*/
    function updateTpe(){
        ini_set('display_errors','on');
        error_reporting(E_ALL);
        $refund_id = empty($_GET['id']) ? 0 : intval($_GET['id']);
        if (!$refund_id) {
            $this->show_warning('缺少参数refund_id', 'back_list', 'index.php?app=refund&act=view&refund_id=' . $refund_id);
            return;
        }
        $refund = $this->_refund_mod->get(array('conditions'=>'refund_id = '.$refund_id));
        $order_info = $this->_order_mod->get($refund['order_id']);
        $type = $_GET['type'];
        $OverSellNum = $_GET['OverSellNum'];
        //同意操作
        if($type == 1){
            $status = 'WAIT_WAREHOUSE_CONFIRM';
            $refund_array = array(
                'OrderNo' => $order_info['order_sn'],
                'Note' => $refund['refund_reason'],
                'CopName' => '',
                'TrackingNo' => '',
                'Action' => 1,
                'RefundsBillNo'=>$refund['refund_sn'],
                'OverSellNum' => $OverSellNum
            );
            $send_array = array(
                'ClientGuid' => CLIENT_GUID,
                'ClientName' => CLIENT_NAME,
                'CustomerRefundsInfo' => $refund_array
            );
            $url = API_URL.'/api/order/CustomerRefunds';
            $this->writeLog('请求OMS：'.$url.'接口开始：报文'.json_encode($send_array));
            $rs = $this->sync_data($url, $send_array);
            $this->writeLog('请求OMS结果：'.$url.'接口开始：结果'.json_encode($rs));
            if(!$rs || $rs['code'] != '200'){
                $this->show_warning('请求OMS失败');
                return;
            }else{
                if($rs['success'] != true) {
                    $this->show_warning($rs['msg']);
                    return;
                }
            }
            $data['status'] = $status;
            if($rs['data']['QueryOrders']['IsCustomerRefunds'] == 1){
                $data['status'] = 'REFUND_GOODS';
                $data['expire_time'] = $refund['created'] + 86400*2;
            }
            $save = $this->_refund_mod->edit($refund_id,$data);

        }else{
            //拒绝操作
            $status = 'CLOSED';
            $data['status'] = $status;
            $save = $this->_refund_mod->edit($refund_id,$data);
        }
        $this->show_message('system_handle_refund_ok', 'back_list', 'index.php?app=refund&act=view&refund_id=' . $refund_id);
    }

    //202-3-10 补偿代金券方案
    function compensate(){
        ini_set('display_errors','on');
        error_reporting(E_ALL);
        $order_id = empty($_GET['order_id']) ? 0 : intval($_GET['order_id']);
        $code = -1;
        $message = '订单id参数错误！';
        if ($order_id) {
            $message = '补偿代金券数量有误！';
            if($_GET['number'] > 0){
                $orderInfo = &m("order")->get(array("conditions"=>"order_id = ".$order_id));
                $message = '订单信息错误！';
                if($orderInfo){
                    $message = '优惠券只可以补偿一次！';
                    //查看是否有过补偿  如没有再进行补偿
                    if($orderInfo['is_compensate'] == 0) {
                        //获取补偿代金券配置
                        $couponInfo = &m("coupon_setting")->get(array("conditions" => 'setting_id = ' . 3));
                        $time = time();

                        for($i=0;$i<$_GET['number'];$i++){
                            $data['coupon_name'] = $couponInfo['name'];
                            $data['money'] = $couponInfo['money'];
                            $data['min_money'] = $couponInfo['min_money'];
                            $data['user_id'] = $orderInfo['buyer_id'];
                            $data['remark'] = $couponInfo['remark'];
                            $data['start_time'] = $time;
                            $data['end_time'] = $couponInfo['expiry_time'] + $time;
                            $data['is_used'] = 0;
                            $data['type'] = $couponInfo['type'];
                            $save = &m("member_coupon")->add($data);
                        }

                        $orderData['is_compensate'] = 1;
                        $saveOrder = &m("order")->edit($orderInfo['order_id'], $orderData);
                        if (!$save || !$saveOrder) {
                            $message = '添加失败';
                            return;
                        } else {
                            $code = 1;
                            $message = '补偿成功';
                            $this->admin_log("增加补偿代金券[" . $_POST['name'] . "]", 1);
                        }
                    }
                }
            }
        }
        $arr['code'] = $code;
        $arr['message'] = $message;
        echo json_encode($arr);
        exit();
    }

    //后台申请退款发送虚拟物流信息
    function searchRefund(){
        $refund_id = $_POST['refund_id'];
        $refund = $this->_refund_mod->get(array('conditions'=>'refund_id = '.$refund_id));
        $order_info = $this->_order_mod->get($refund['order_id']);

        mt_srand((double) microtime() * 1000000);
        $timestamp = gmtime();
        $y = date('Y', $timestamp);
        $z = date('z', $timestamp);
        $refund_sn = 'R'.$y . str_pad($z, 3, '0', STR_PAD_LEFT) . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);

        $refund_array = array(
            'OrderNo' => $order_info['order_sn'],
            'Note' => $refund['refund_reason'],
            'CopName' => '自理物流公司',
            'TrackingNo' => $refund_sn,
            'Action' => 2,
            'RefundsBillNo'=>$refund['refund_sn'],
            'OverSellNum' => $order_info['OverSellNum']
        );
        $send_array = array(
            'ClientGuid' => CLIENT_GUID,
            'ClientName' => CLIENT_NAME,
            'CustomerRefundsInfo' => $refund_array
        );
        $url = API_URL.'/api/order/CustomerRefunds';
        $this->writeLog('请求OMS：'.$url.'接口开始：报文'.json_encode($send_array));
        $rs = $this->sync_data($url, $send_array);
        $this->writeLog('请求OMS结果：'.$url.'接口开始：结果'.json_encode($rs));
        if(!$rs || $rs['code'] != '200'){
            $arr['msg'] = '请求oms失败！';
        }else{
            if($rs['success'] != true) {
                $arr['msg'] = $rs['msg'];
            }else{
                $arr['msg '] = '操作成功！';
            }
        }
        echo json_encode($arr);
        exit();
    }


    function writeLog($mes)
    {
        $years = date('Y-m-d');
        //设置路径目录信息
        $url  = '../temp/logs/'.$years.'/'.$years.'_request_log.txt';
        //取出目录路径中目录(不包括后面的文件)
        $dir_name = dirname($url);
        //如果目录不存在就创建
        if(!file_exists($dir_name)) {
            $res = mkdir(iconv("UTF-8","GBK",$dir_name),0777,true);
        }
        file_put_contents($url,date('Y-m-d H:i:s').":".$mes."\n",FILE_APPEND);
    }




}

?>
